package com.core.common.utils.springutils;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.ServletContextAware;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.condition.PatternsRequestCondition;
import org.springframework.web.servlet.mvc.condition.RequestMethodsRequestCondition;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import javax.servlet.ServletContext;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @program: YJ-admin
 * @description: 获取所有路径映射
 * @author: honglei
 * @create: 2022-04-08 16:45
 */
@Service
public class InitUrlService implements InitializingBean, ServletContextAware {

    public static List<HashMap<String, String>> urlList = new ArrayList<HashMap<String, String>>();

    @Autowired
    private RequestMappingHandlerMapping requestMappingHandlerMapping;

    /**
     * 获取url与类和方法的对应信息
     */
    @Override
    public void setServletContext(ServletContext servletContext) {
        Map<RequestMappingInfo, HandlerMethod> handlerMethodsMap = requestMappingHandlerMapping.getHandlerMethods();
        for (Map.Entry<RequestMappingInfo, HandlerMethod> item : handlerMethodsMap.entrySet()) {
            HashMap<String, String> model = new HashMap<String, String>();
            RequestMappingInfo info = item.getKey();
            HandlerMethod method = item.getValue();
            PatternsRequestCondition p = info.getPatternsCondition();
            for (String url : p.getPatterns()) {
                model.put("url", url);  //路径
            }

            model.put("className", method.getMethod().getDeclaringClass().getName()); // 类名

            RestController apiOperation = method.getMethodAnnotation(RestController.class);
            if (apiOperation != null) {
//                model.put("apiOperationValue", apiOperation.value()); //接口说明
//                model.put("apiOperationnotes", apiOperation.notes()); //接口发布说明
            }

            RequestMethodsRequestCondition methodsCondition = info.getMethodsCondition();
            String type = methodsCondition.toString();
            if (type != null && type.startsWith("[") && type.endsWith("]")) {
                type = type.substring(1, type.length() - 1);
                model.put("type", type); // 方法请求类型
            }
            urlList.add(model);
        }

        System.out.println("----反向加载URL完成----");
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        //

    }


}
